package com.fsnbigdata.service.impl;

import com.fsnbigdata.domain.ZhExpert;
import com.fsnbigdata.repository.ZhExpertRepository;
import com.fsnbigdata.service.api.ZhExpertService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: chen quan zhou
 * @Date: Created in 19:07 2018/9/29
 * @Modified By:
 */

@Service
public class ZhExpertServiceImpl implements ZhExpertService{
    
    @Autowired
    private ZhExpertRepository zhExpertRepository;
    
    @Override
    public ZhExpert findById(Long id) {
        return zhExpertRepository.findOne(id);
    }
    
    @Override
    public ZhExpert save(ZhExpert zhExpert) {
        return zhExpertRepository.save(zhExpert);
    }
    
    @Override
    public List<ZhExpert> findAll(String creator) {
        return zhExpertRepository.getListByCreator(creator);
    }
    
    @Override
    public void deleteOne(Long id) {
        zhExpertRepository.delete(id);
    }
    
    @Override
    public void delete(Iterable<Long> ids) {
        List<ZhExpert> zhExperts = zhExpertRepository.findAll(ids);
        zhExpertRepository.deleteInBatch(zhExperts);
    }
    
    @Override
    public ZhExpert update(ZhExpert zhExpert) {
        return zhExpertRepository.save(zhExpert);
    }
    
    public Page<ZhExpert> findByPageAndSize(String name, Pageable pageable){
        Specification<ZhExpert> specification = new Specification<ZhExpert>() {
            @Override
            public Predicate toPredicate(Root<ZhExpert> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                if (StringUtils.isNotBlank(name)){
                    Path<String> _name = root.get("name");
                    Predicate _key = cb.like(_name, "%" + name + "%");
                    return cb.and(_key);
                }
                return cb.and();
            }
        };
        return zhExpertRepository.findAll(specification,pageable);
    }
    
    @Override
    public List<ZhExpert> findAllByType(Integer type) {
        return zhExpertRepository.findAllByType(type);
    }

    @Override
    public List queryList(String type, Pageable pageable) {
        List list = new ArrayList(  );
        list.add( zhExpertRepository.getCount(type) );
        list.add( zhExpertRepository.queryList( type,pageable ) );
        return list;
    }

}
